package com.timber.panels;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;

import pv.jfcx.JPVCurrency;

import com.borland.jbcl.layout.VerticalFlowLayout;
import com.timber.frame.ImsFrame;
import com.timber.util.BillBean;
import com.timber.util.BillTableModel;
import com.timber.util.ITPEdit;
import com.timber.util.ImageMgr;
import com.timber.util.ImsFrameComponent;
import com.timber.util.InvoiceMgr;
import com.timber.util.PaymentBean;
import com.timber.util.PaymentMgr;
import com.timber.util.PaymentTableModel;
import com.timber.util.SLTablePrinter;
import com.timber.util.SLTableView;
import com.timber.util.SalesOrderManager;
import com.timber.util.Util;

public class BillAdjustmentPanel extends ImsFrameComponent {
	protected BillTableModel	lnDetailModel = new BillTableModel();  
	protected PaymentTableModel	paymentDetailModel = new PaymentTableModel();  
	protected Component			hstrut =  Box.createRigidArea(new Dimension(580,20));
	protected BorderLayout		borderLayout1 = new BorderLayout();
	protected JPanel			topPanel = new JPanel();
	protected JPanel			topPanel2 = new JPanel();
	protected JPanel			bottompanel = new JPanel();
	protected GridBagLayout		gridBagLayout1 = new GridBagLayout();
	protected JPanel			centerPanel = new JPanel();
	protected Border			border1;
	protected TitledBorder		titledBorder1;
	protected GridBagLayout		gridBagLayout2 = new GridBagLayout();
	protected GridBagLayout	 gridBagLayout3=new GridBagLayout();
	private Font tableFont = new Font("DialogInput", Font.BOLD, 16);
	
	
	protected JPanel			btnPanel = new JPanel();
	protected JPanel			btnHolder = new JPanel();
	protected VerticalFlowLayout		verticalFlowLayout1 = new VerticalFlowLayout();
	protected VerticalFlowLayout		verticalFlowLayout = new VerticalFlowLayout();
	protected FlowLayout			flowLayout1 = new FlowLayout();
	protected FlowLayout			flowLayout2 = new FlowLayout();
	protected JButton			clearBtn = new JButton();
	protected JButton			goBtn = new JButton();
	protected JButton			saveBtn = new JButton();
	protected JButton			printBtn = new JButton();
	protected ImageIcon			goImage;
	protected ImageIcon			saveImage;
	protected ImageIcon			printImage;
	protected ImageIcon			clearAllImage;
	
	protected SLTableView			inDetailTV = new SLTableView( lnDetailModel );
	protected SLTableView			paymentDetailTV = new SLTableView( paymentDetailModel );
	protected SLTablePrinter		aPrinter;
	protected Color			focusCellColor = new Color( 204, 204, 255 );
	private   JMenuItem                   deleteAction  = new JMenuItem("Delete");
	private   JMenuItem                   updateAction  = new JMenuItem("Update");
	
	public JPanel					ratePanel					= new JPanel();  
	
	//	  protected JPVCurrency totalTF = new JPVCurrency();
	//	  protected JLabel 	totalLabel;
	//	  
	
	protected JPVCurrency GrandTotalTF = new JPVCurrency();
	protected JPVCurrency BalanceAmountTF = new JPVCurrency();
	protected ITPEdit CustomerNameTF = new  ITPEdit();
	protected JPVCurrency PayAmountTF = new JPVCurrency();
	
	protected JLabel GrandTotalLabel; 
	protected JLabel BalancesAmountLabel; 
	protected JLabel CustomerLabel; 
	protected JLabel PayAmountLabel; 
	protected JLabel TotalBillAmountLabel; 
	BilliAdjPanel objBillinfoPanel;
	protected JPanel			buttonPanel = new JPanel();
	int invoiceNumber =0;
	int selectedRow=0;
	Vector v=new Vector() ;
	Vector pv=new Vector() ;
	protected JPVCurrency TotalBillAmountTF = new JPVCurrency();
	 
	
	
	public BillAdjustmentPanel( ImsFrame parent )
	{
		super( parent );
		try
		{
			jbInit();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	void jbInit() throws Exception
	{
		
		GrandTotalTF.setSymbol("RS ");
		PayAmountTF.setSymbol("RS ");
		BalanceAmountTF.setSymbol("RS ");
		BalanceAmountTF.size();
		TotalBillAmountTF.setSymbol("RS ");
		invoiceNumber=0;
		
		
		GrandTotalTF.setSize(new Dimension(180,25));
		PayAmountTF.setSize(new Dimension(180,25));
		CustomerNameTF.setSize(new Dimension(180,25));
		
		CustomerNameTF.setFont(tableFont);
		PayAmountTF.setFont(tableFont);
		
		// buttonPanel.setLayout( verticalFlowLayout1 );
		objBillinfoPanel=new BilliAdjPanel( parent, true);
		goImage       = ImageMgr.getIcon( ImageMgr.GO32_ICON );
		clearAllImage = ImageMgr.getIcon( ImageMgr.CLEARALL32_ICON );
		saveImage= ImageMgr.getIcon( ImageMgr.SAVE24_ICON );
		printImage=ImageMgr.getIcon( ImageMgr.PRINT32_ICON );
		// this.setLayout( flowLayout2 );
		this.setLayout( borderLayout1 );
		//this.setLayout( verticalFlowLayout1 );
		border1 = BorderFactory.createEtchedBorder( Color.white, new Color( 142, 142, 142 ) );
		titledBorder1 = new TitledBorder( border1, " Bill Details" );
		topPanel.setLayout( gridBagLayout1 );
		topPanel2.setLayout( gridBagLayout3 );
		
		centerPanel.setBorder( titledBorder1 );
		//centerPanel.setLayout( gridBagLayout2 );
		centerPanel.setLayout( flowLayout2 );
		
		
		btnHolder.setLayout( verticalFlowLayout1 );
		
		flowLayout1.setAlignment( FlowLayout.RIGHT );
		flowLayout2.setAlignment( FlowLayout.LEFT );
		btnPanel.setLayout( flowLayout1 );
		
		
		
		
		saveBtn.setIcon( saveImage );
		saveBtn.setMargin( new Insets( 0, 0, 0, 0 ) );
		saveBtn.addActionListener( new ActionListener()
				{
			public void actionPerformed( ActionEvent e )
			{
				SaveActions( );
			}
			
			
				} );
		
		
		printBtn.setIcon( printImage );
		printBtn.setMargin( new Insets( 0, 0, 0, 0 ) );
		printBtn.addActionListener( new ActionListener()
				{
			public void actionPerformed( ActionEvent e )
			{
				printTable(  e);
				
			}
			
			
				} );
		
		
		goBtn.setIcon( goImage );
		goBtn.setMargin( new Insets( 0, 0, 0, 0 ) );
		goBtn.addActionListener( new ActionListener()
				{
			public void actionPerformed( ActionEvent e )
			{
				searchInvoice( );
			}
			
			
				} );
		
		clearBtn.setIcon( clearAllImage );
		clearBtn.setMargin( new Insets( 0, 0, 0, 0 ) );
		clearBtn.setToolTipText( "Clear All" );
		clearBtn.addActionListener( new ActionListener()
				{
			public void actionPerformed( ActionEvent e )
			{
				clear();
			}
			
			private void clear() {
				System.out.println("Called clear option");
				
			}
				} );
		GrandTotalLabel=new JLabel("Total Paid Amount"); 
		BalancesAmountLabel=new JLabel("Balance Amount"); 
		CustomerLabel=new JLabel("Customer Name"); 
		PayAmountLabel=new JLabel("Paying Amount"); 
		TotalBillAmountLabel = new  JLabel("Bill Amount");
		Dimension d = new Dimension(80,20);
		this.add( topPanel, BorderLayout.NORTH );
		
		// calculating Qty on change of legth or width
		
		
		//TODO
		
		
		topPanel.add( objBillinfoPanel,
				new GridBagConstraints( 5,
						0,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.SOUTHWEST,
						GridBagConstraints.NONE,
						new Insets( 12, 10, 0, 0 ), 0, 0 ) );
		
		
		topPanel.add( btnPanel,
				new GridBagConstraints( 8,
						0,
						GridBagConstraints.REMAINDER,
						GridBagConstraints.REMAINDER,
						100.0,
						100.0,
						GridBagConstraints.CENTER,
						GridBagConstraints.BOTH,
						new Insets( 5, 10, 0, 0 ), 0, 0 ) );
		
		
		bottompanel.add( CustomerLabel,
				new GridBagConstraints( 0,
						1,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.EAST,
						GridBagConstraints.NONE,
						new Insets( 5, 5, 0, 0 ), 0, 0 ) );
		
		bottompanel.add( CustomerNameTF,
				new GridBagConstraints( 0,
						1,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.EAST,
						GridBagConstraints.NONE,
						new Insets( 5, 5, 0, 0 ), 0, 0 ) );
		bottompanel.add( PayAmountLabel,
				new GridBagConstraints( 0,
						2,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.EAST,
						GridBagConstraints.NONE,
						new Insets( 5, 5, 0, 0 ), 0, 0 ) );
		
		bottompanel.add( PayAmountTF,
				new GridBagConstraints( 0,
						2,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.EAST,
						GridBagConstraints.NONE,
						new Insets( 5, 5, 0, 0 ), 0, 0 ) );
		
	
		bottompanel.add( saveBtn,
				new GridBagConstraints( 1,
						2,
						1,
						1,
						0.0,
						0.0,
						GridBagConstraints.EAST,
						GridBagConstraints.NONE,
						new Insets( 5, 5, 0, 0 ), 0, 0 ) );
		
		btnPanel.add(btnHolder, null);
		btnHolder.add(goBtn, null);
		btnHolder.add(clearBtn, null);
		//btnHolder.add(saveBtn, null);
		btnHolder.add(printBtn, null);
		
		
		
		
		this.add( centerPanel, BorderLayout.CENTER );
		
		
		deleteAction.addActionListener(new java.awt.event.ActionListener(){
			public void actionPerformed(ActionEvent e) {
				delete_actionPerformed(e);
			}
			
			private void delete_actionPerformed(ActionEvent e) {
				System.out.println("delete_actionPerformed event is called ");
				
				int selectedRow = inDetailTV.getTable().getSelectedRow();
				
				BillTableModel tm = (BillTableModel) inDetailTV.getTable().getModel();
				BillBean iteamBean = (BillBean) tm.itemAtTableRow(selectedRow);
				
				Util.log( "ItemMgr.Detele is calling()" +iteamBean.getItemId());
				if (iteamBean.getItemId()!=null)
				{
					SalesOrderManager.deleteSalesOrder(iteamBean);
					
					((BillTableModel) inDetailTV.getTable().getModel()).removeRow(selectedRow);
				}
				
			}
		});
		updateAction.addActionListener(new java.awt.event.ActionListener(){
			public void actionPerformed(ActionEvent e) {
				update_actionPerformed(e);
			}
			
			private void update_actionPerformed(ActionEvent e) {
				System.out.println("update_actionPerformed event is called ");
				System.out.println("Look up corp Action called ");
				BillBean obj1=new BillBean();
				// poplauting bean object from billpanel
				selectedRow = inDetailTV.getTable().getSelectedRow();
				BillTableModel tm = (BillTableModel) inDetailTV.getTable().getModel();
				obj1 = (BillBean) tm.itemAtTableRow(selectedRow);
				objBillinfoPanel.billNumTF.setText(obj1.getItemId());
				objBillinfoPanel.ItemNameTF.setText(obj1.getTimberName());
				objBillinfoPanel.ItemClassTF.setText(obj1.getTimberName());
				objBillinfoPanel.LengthTF.setDouble(obj1.getLenght());
				objBillinfoPanel.widthTF.setDouble(obj1.getWidth());
				objBillinfoPanel.rateTF.setDouble(obj1.getSalesRate());
				objBillinfoPanel.qtyTF.setDouble(obj1.getSQuantity());
				objBillinfoPanel.taxTF.setDouble(obj1.getTax());
				objBillinfoPanel.totalTF.setDouble(obj1.getTotal());
				
			}
		});
		
		setUpInDetailTV();
		addInDetailTV();
		
		setpaymentDetailTV();
		addpaymentDetailTV();
		
		this.add( bottompanel,BorderLayout.SOUTH);
		
		
	}
	
	
	protected void setUpInDetailTV()
	{
		
		inDetailTV.setSize(new Dimension(1350,300));
		inDetailTV.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
		inDetailTV.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		inDetailTV.setEditable( false );
		inDetailTV.setEnableSortData( true );
		inDetailTV.setSortingNulls( true );
		inDetailTV.setShowSortIcons( true );
		inDetailTV.setScrollAfterSort( false );
		inDetailTV.getTable().setRowSelectionAllowed( true );
		inDetailTV.getTable().setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
		inDetailTV.setFocusCellBackground( focusCellColor );
		
		inDetailTV.getPopupMenu().add(deleteAction);
		inDetailTV.getPopupMenu().add(updateAction);
		inDetailTV.addRowSelectionListener(new javax.swing.event.ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				// Update security
				int selectedRow = inDetailTV.getTable().getSelectedRow();
				//CorporateAction ca = getSelectedItem(selectedRow);
				
				//	            if (ca != null) {
				//	                if (ca.seid != currSeId) {
				//	                    SecurityObj secObj = SecurityMgr.getSingleSecurity(Integer.toString(ca.seid),"DB_IMS");
				//	                    getSecClass().setClassification(secObj);
				//
				//	                    currSeId = ca.seid;
				//	                }
				//	            }
			}
		});
		
		inDetailTV.getTable().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent me) {
				if (SwingUtilities.isLeftMouseButton(me)) {
					Point point = me.getPoint();
					
					if (me.getClickCount() == 2) {
						
						//							corpActTblDoSelect(inDetailTV.getTable().rowAtPoint(
						//									point), inDetailTV.getTable().columnAtPoint(
						//									point));
					}
					
				}
			}
		});
		
		
	}
	
	
	protected void setpaymentDetailTV()
	{
		paymentDetailTV.setSize(new Dimension(1350,150));
		paymentDetailTV.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
		paymentDetailTV.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		paymentDetailTV.setEditable( false );
		paymentDetailTV.setEnableSortData( true );
		paymentDetailTV.setSortingNulls( true );
		paymentDetailTV.setShowSortIcons( true );
		paymentDetailTV.setScrollAfterSort( false );
		paymentDetailTV.getTable().setRowSelectionAllowed( true );
		paymentDetailTV.getTable().setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
		paymentDetailTV.setFocusCellBackground( focusCellColor );
		
		paymentDetailTV.getPopupMenu().add(deleteAction);
		paymentDetailTV.getPopupMenu().add(updateAction);
		paymentDetailTV.addRowSelectionListener(new javax.swing.event.ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				// Update security
				int selectedRow = inDetailTV.getTable().getSelectedRow();
			}
		});
		
		paymentDetailTV.getTable().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent me) {
				if (SwingUtilities.isLeftMouseButton(me)) {
					Point point = me.getPoint();
					
					if (me.getClickCount() == 2) {
						
					}
					
				}
			}
		});
		
		
	}
	

	
	

	
	protected void addInDetailTV()
	{


		
		centerPanel.add( inDetailTV,null);
		centerPanel.validate();
	}
	
	protected void addpaymentDetailTV()
	{

		centerPanel.add( paymentDetailTV,null);
		centerPanel.validate();
		
		centerPanel.add( BalancesAmountLabel,null);
		BalanceAmountTF.setSize(new Dimension(180,25));
//		BalanceAmountTF.setBackground(Color.yellow);
		BalanceAmountTF.setFont(tableFont);
		
		centerPanel.add( BalanceAmountTF,null);
		centerPanel.add( GrandTotalLabel,null);
		GrandTotalTF.setSize(new Dimension(180,25));
//		GrandTotalTF.setBackground(Color.yellow);
		GrandTotalTF.setFont(tableFont);
		centerPanel.add( GrandTotalTF,null);
		centerPanel.add( TotalBillAmountLabel,null);
		TotalBillAmountTF.setSize(new Dimension(180,25));
		centerPanel.add( TotalBillAmountTF,null);
//		TotalBillAmountTF.setBackground(Color.yellow);
		TotalBillAmountTF.setFont(tableFont);
	}
	
	private void searchInvoice() {
		
		double totalPaidAmount=0;;
		double billAmount=0;
		double balanceAmount=0;
		InvoiceMgr invoiceMgr = new InvoiceMgr();
		PaymentMgr paymentMgr = new PaymentMgr();
		v=invoiceMgr.getInviceDetails(objBillinfoPanel.billNumTF.getText());
		lnDetailModel.setTableData(v);	
		lnDetailModel.fireTableDataChanged();
		// bill amount 
		if(v!=null)
		{
			for(int i=0;i<v.size();i++ )
			{
				BillBean obj = (BillBean)v.get(i);
				billAmount =billAmount+obj.getAmount();
				System.out.println("billAmount :"+billAmount);
			}
			TotalBillAmountTF.setDouble(billAmount);
		}
		
		//payment detaild getting
		pv = paymentMgr.getPaymentDetails(objBillinfoPanel.billNumTF.getText());
		paymentDetailModel.setTableData(pv);	
		paymentDetailModel.fireTableDataChanged();
		// get total paid amount
		if(pv!=null)
		{
			for(int i=0;i<pv.size();i++ )
			{
				PaymentBean obj = (PaymentBean)pv.get(i);
				totalPaidAmount =totalPaidAmount+obj.getPaymentAmount();
				System.out.println("totalPaidAmount :"+totalPaidAmount);
			}
			GrandTotalTF.setDouble(totalPaidAmount);
		}
		// balance amount calaculation 
		balanceAmount = billAmount-totalPaidAmount;
		BalanceAmountTF.setDouble(balanceAmount);
		
	}
	
	private void calGrandTotal() {
		int size= v.size();
		double gtotal=0;
		BillBean obj1;
		if(size>=1)
		{
			for (int i=0;i<size;i++)
			{
				obj1=(BillBean)v.get(i);
				
				gtotal+=obj1.getAmount();
				System.out.println("--->"+gtotal);
			}
			GrandTotalTF.setDouble(gtotal); 
		}
		
	}
	
	private void SaveActions()
	{
		System.out.println("Save action called ");
		SalesOrderManager.insertPayment(objBillinfoPanel.billNumTF.getText(),CustomerNameTF.getText(),GrandTotalTF.getDouble(),PayAmountTF.getDouble());
	}
	
	
	private void PrintActions()
	{
		System.out.println("Print action");
	}
	
	
	
	private void printTable(ActionEvent e) {
		try{
			if( this.lnDetailModel.getRowCount() > 0 ) {
				SLTablePrinter	aPrinter = new SLTablePrinter( this.lnDetailModel, "Bill No  :" +invoiceNumber +" ",
						SLTablePrinter.PORTRAIT );
				System.out.println("Print action");
				aPrinter.setMargin( 0.95, 0.5, 0.7, 0.5 );
				aPrinter.setFit2Page( false );
				aPrinter.setFontSize( 8 );
				aPrinter.printWithDialog();
			}
			else{
				JOptionPane.showMessageDialog( this,"Table has no rows to print.",
						"Nothing to print.",
						JOptionPane.ERROR_MESSAGE );
			}
		}
		catch (Exception ex){
			JOptionPane.showMessageDialog(this, "Error occured while printing Exceptions List.\nPlease contact iDelta technical support.",
					"Error", JOptionPane.OK_OPTION);
		}
	}
	
}
